// 监听插件icon被点击
chrome.browserAction.onClicked.addListener(function (tab) {
    chrome.tabs.executeScript({
        code: 'alert("Icon clicked!")'
    });
    //alert("hello world");

    //截图


    // 请求截屏
    /*chrome.tabs.captureVisibleTab(null, {}, function(img) {
        const screenshotUrl = img;

        chrome.downloads.download({
            url: screenshotUrl,
            filename: 'screenshot.png'
        });
    });*/

    chrome.tabs.sendMessage(tab.id, {evt: "start"}, function (response) {
        console.log(response);
    });

});


chrome.runtime.onMessage.addListener(function (request, sender, sendResponse) {
    console.log(sender.tab ? "from a content script:" + sender.tab.url : "from the extension");
    if (request.evt == "capture") {
        console.log(request.x + ":" + request.y);
        console.log(request.w + ":" + request.h);

        chrome.tabs.captureVisibleTab(null, {format: "png", quality: 100},
            function (dataUrl) {
                // 用 HTML5 Canvas 对屏幕截图进行处理
                var image = new Image();
                image.onload = function () {
                    // 创建一个 Canvas 元素
                    var canvas = document.createElement('canvas');

                    // 计算需要截取的区域
                    // 这里只是示例，需要根据实际需求计算截图区域的位置和大小
                    var left = request.x, top = request.y, width = request.w, height = request.h;

                    // 设置 Canvas 大小为截图大小
                    canvas.width = width;
                    canvas.height = height;

                    // 从图片中截取指定区域
                    var context = canvas.getContext('2d');
                    //context.strokeStyle = "red";
                    context.drawImage(image, left, top, width, height, 0, 0, width, height);

                    // 将截取的图片显示到页面上（这里只是简单地放在页面最前面）
                    var base64Img = canvas.toDataURL("image/png");
                    console.log(base64Img);

                    var formData = new FormData();
                    formData.append("base64Image", base64Img);
                    formData.append("language", "eng");
                    formData.append("apikey", "K88294794488957");
                    //formData.append("apiKey", "copyfishonly23cr");
                    $.ajax({
                        url: "https://api.ocr.space/Parse/Image",
                        //url: "https://apipro1.ocr.space/parse/image",
                        data: formData,
                        dataType: 'json',
                        cache: false,
                        contentType: false,
                        processData: false,
                        type: 'POST',
                        success: function (data) {
                            if (data.ParsedResults.length > 0) {
                                console.log(data.ParsedResults[0].ParsedText);
                                sendResponse(data.ParsedResults[0].ParsedText);
                                //sendResponse('我是后台，我已收到你的消息：' + JSON.stringify(data));
                            }
                        }
                    })
                };
                // 加载屏幕截图
                image.src = dataUrl;
            });
        return true;  // Will respond asynchronously.
    }
});


